const { query, body, param } = require('express-validator')
const { validResultCallback } = require('../../middleware')
const { validInt, validReg } = require('../../utils/validator')

const getCategorysValidator = [
  validInt(query, 'page'),
  validInt(query, 'limit'),
  validReg(query, 'status', /^[01]$/),
  validResultCallback
]

const createCategoryValidator = [
  body('pid', 'pid 格式错误')
    .if(body('pid').exists({ checkFalsy: true }))
    .custom(v => /^\d+$/.test(v)),
  body('name')
    .exists({ checkFalsy: true })
    .withMessage('name 未传')
    .bail()
    .isString()
    .withMessage('name 格式错误'),
  body('order')
    .exists()
    .withMessage('order 未传')
    .custom(v => typeof v === 'number')
    .withMessage('order 格式错误'),
  body('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => [0, 1].includes(value))
    .withMessage('status 格式错误'),
  validResultCallback
]

const updateCategoryValidator = [
  body('pid', 'pid 格式错误')
    .if(body('pid').exists({ checkFalsy: true }))
    .custom(v => /^\d+$/.test(v)),
  body('name')
    .exists({ checkFalsy: true })
    .withMessage('name 未传')
    .bail()
    .isString()
    .withMessage('name 格式错误'),
  body('order')
    .exists()
    .withMessage('order 未传')
    .custom(v => typeof v === 'number')
    .withMessage('order 格式错误'),
  body('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => [0, 1].includes(value))
    .withMessage('status 格式错误'),
  validResultCallback
]

const statusValidator = [
  param('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => ['0', '1'].includes(value))
    .withMessage('status 格式错误'),
  validResultCallback
]

module.exports = {
  getCategorysValidator,
  createCategoryValidator,
  updateCategoryValidator,
  statusValidator
}
